import 'package:flutter/material.dart';
import 'dart:io';

import 'package:flutter/services.dart';

// 文章参考
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // static const platform =
  // const MethodChannel("com.example.flutter_android_connect");
  var _data = "获取数据";
  var platforms = [];
  @override
  Widget build(BuildContext context) {
    Widget platformView() {
      if (Platform.isAndroid) {
        return AndroidView(
          viewType: 'plugins.flutter.io/custom_platform_view',
          onPlatformViewCreated: (viewId) {
            print('viewId:$viewId');
            platforms.add(MethodChannel(
                'com.example.flutter_android_connect.MyFlutterView_$viewId'));
          },
          creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
          creationParamsCodec: StandardMessageCodec(),
        );
      } else
        return Container(child: Text("非andorid平台"));
    }

    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              // platform.invokeMethod("setText", {'name': 'ggb', 'age': 18});
              // platform.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
              platforms[0]
                  .invokeMethod('setText', {'name': 'laomeng', 'age': 18});
            },
            child: Text("传递参数给原生view"),
          ),
          ElevatedButton(
            onPressed: () async {
              // platform.invokeMethod("setText", {'name': 'ggb', 'age': 18});
              var result = await platforms[0]
                  .invokeMethod('getData', {'name': 'laomeng', 'age': 18});
              setState(() {
                _data = "${result['name']},${result['age']}";
              });
              print(_data);
            },
            child: Text("$_data"),
          ),
          Expanded(child: Container(color: Colors.red, child: platformView())),
          Expanded(child: Container(color: Colors.blue, child: platformView())),
          Expanded(
              child: Container(color: Colors.yellow, child: platformView())),
        ],
      ),
    );
  }
}
